import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ModalBehavior from '../../base/behaviors/ModalBehavior.js';
import SelectWidget from '../../widgets/SelectWidget.js';
import {
    serializeForm
} from '../../tools.js';
import {
    formatAmount
} from '../../math.js';

const SupplierInvoiceLineDuplicateFormView = Mn.View.extend({
    id: 'supplierorderline-duplicate-form',
    behaviors: [ModalBehavior],
    template: require('./templates/SupplierInvoiceLineDuplicateFormView.mustache'),
    regions: {
        'select': '.select'
    },
    ui: {
        cancel_btn: 'button[type=reset]',
        form: 'form',
    },
    events: {
        'submit @ui.form': 'onSubmit',
        'click @ui.cancel_btn': 'onCancelClick',
    },
    initialize() {
        var channel = Radio.channel('config');
        this.options = channel.request('get:options', 'supplier_invoices');
    },
    onCancelClick() {
        this.triggerMethod('modal:close');
    },
    templateContext() {
        var ht = this.model.getHT();
        var tva = this.model.getTva();
        var ttc = this.model.total();
        return {
            ht: formatAmount(ht),
            tva: formatAmount(tva),
            ttc: formatAmount(ttc),
            type_id: this.model.get('type_id'),
        };
    },
    onRender() {
        var view = new SelectWidget({
            options: this.options,
            title: 'Facture fournisseur vers laquelle dupliquer',
            id_key: 'id',
            field_name: 'supplier_invoice_id',
            value: this.model.get('supplier_invoice_id'),
        });
        this.showChildView('select', view);
    },
    onSubmit(event) {
        event.preventDefault();
        var datas = serializeForm(this.getUI('form'));
        var request = this.model.duplicate(datas);
        var that = this;
        request.done(function () {
            that.triggerMethod('modal:close');
        });
    },
});
export default SupplierInvoiceLineDuplicateFormView;